#pragma once
#include<jsoncpp/json/json.h>
#include"index.hpp"
namespace nasearchar
{
    class Searchar
    {
ns_index::Index*myindex;
public:
Searchar(){}
~Searchar(){}
bool Init(const std::string&input)
{
myindex=ns_index::Index::getIndex();
std::cout<<"get index"<<std::endl;
myindex->BuildIndex(input);
std::cout<<"build over"<<std::endl;
return true;
}

bool Search(std::string&clientsay,std::string&jsonstring)
{
  std::vector<std::string>word;
  util::jiebautil::CutString(clientsay,word);
 ns_index:: InvertList all;
  for(auto&e:word)
  {
    boost::to_lower(e);
    ns_index::InvertList*now=myindex->Getinvert(e);
if(now==nullptr)
{
    continue;
}
all.insert(all.end(),now->begin(),now->end());
  }
std::sort(all.begin(),all.end(),[](const ns_index::Invert& a, const ns_index::Invert& b) {  
    return a.weight > b.weight;  
});
std::vector<ns_index::DocInfo> gettext;
Json::Value root;
int count=0;
for(auto&e:all)
{
    count++;
    ns_index::DocInfo*now;
    now=myindex->Getforward(e.id);
Json::Value elem;
elem["title"]=now->title;
elem["des"]=getrebody(now->body,e.word);
elem["url"]=now->url;
elem["weight"]=e.weight;
root.append(elem);
if(count>=20)
break;
}
Json::StyledWriter writer;
jsonstring=writer.write(root);
}
std::string getrebody(std::string&body,const std::string&word)
{
#define front 50
#define before 100
    int  pos=body.find(word);
    int fcut;
    int endcut;
     if(pos<front)
     {
fcut=0;
     }
     else
     {
        fcut=pos-front;
     }
     if(before+pos>=body.size())
     {
        endcut=body.size()-1;
     }
     else
     {
     endcut=pos+before;
     }
     std::string en;
     en=body.substr(fcut,endcut-fcut);
     if(endcut!=body.size()-1)
{
    en+="...";
}
     return en;
}
    };
}